package com.kafka.provider;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.admin.AdminClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.ExecutionException;

// 消息提供者
@Component
@Slf4j
public class KafkaProvider {


//    @Autowired
//    private AdminClient adminClient;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendChatMsg(String topic, String key, String message) throws ExecutionException, InterruptedException {
        ListenableFuture<SendResult<String, String>> Msg = kafkaTemplate.send(topic, key, message);

        Msg.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable throwable) {
                log.info("发送消息失败！");
                kafkaTemplate.send(topic, key, message);
            }

            @Override
            public void onSuccess(SendResult<String, String> stringStringSendResult) {
                //log.info("发送消息成功！");
            }
        });

        // 发送消息
        // topic-->msg[0]   key-->msg[1]    data-->msg[2]
//        ListenableFuture<SendResult<String, String>> Msg = null;
//        for (String TP : adminClient.listTopics().names().get()) {
//            if (msg[0].equals(TP)){
//                Msg =  kafkaTemplate.send(msg[0], msg[1], msg[2]);
//            }
//        }

        // 监听回调


    }


//    public  void sendChatMsg(DataContent dataContent) {
//        // 发送消息
//        ListenableFuture<SendResult<String, String>> Msg = kafkaTemplate.send(TopicMsg, JSONObject.toJSONString(dataContent));
//        // 监听回调
//        Msg.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
//            @Override
//            public void onFailure(Throwable throwable) {
//            }
//            @Override
//            public void onSuccess(SendResult<String, String> result) {
//            }
//        });
//    }
//
//    public  void sendFriendsRequest(FriendsRequest friendsRequest) {
//        // 发送消息
//        ListenableFuture<SendResult<String, String>> request = kafkaTemplate.send(TopicRequest, JSONObject.toJSONString(friendsRequest));
//        // 监听回调
//        request.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
//            @Override
//            public void onFailure(Throwable throwable) {
//            }
//            @Override
//            public void onSuccess(SendResult<String, String> result) {
//            }
//        });
//    }


}
